package com.hjh.testdemo.ui.usb.host

import android.hardware.usb.UsbConstants
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbEndpoint
import android.hardware.usb.UsbInterface
import androidx.fragment.app.viewModels
import com.hjh.core.activity.BaseFragment
import com.hjh.testdemo.databinding.FragmentUsbDeviceInfoBinding
import kotlin.getValue
import kotlin.let

/**
 * @author： hjh
 * @createDate： 2025/6/17 14:14
 * @description：
 * @qq： 3472903821
 * @version: 1.0
 */
class UsbDeviceInfoFragment : BaseFragment<FragmentUsbDeviceInfoBinding>() {

    private var usbDevice: UsbDevice? = null
    private val viewModel: UsbHostViewModel by viewModels({ requireParentFragment() })

    override fun initView() {
        this.usbDevice = viewModel.usbSerialDriver.value?.device
        usbDevice?.let { device ->
            val baseInfo = """
                设备名称: ${device.deviceName}
                DeviceId: ${device.deviceId}
                VendorId: ${device.vendorId}
                ProductId: ${device.productId}
                DeviceClass: ${device.deviceClass}
                DeviceSubClass: ${device.deviceSubclass}
                DeviceProtocol: ${device.deviceProtocol}
                InterfaceCount: ${device.interfaceCount}
                HasPermission: ${device.deviceId != 0}
                SerialNumber: ${device.serialNumber ?: "无"}
                ManufacturerName: ${device.manufacturerName ?: "无"}
                ProductName: ${device.productName ?: "无"}
            """.trimIndent()

            val detailBuilder = StringBuilder()
            for (i in 0 until device.interfaceCount) {
                val usbInterface: UsbInterface = device.getInterface(i)
                detailBuilder.append("▶ 接口 $i\n")
                detailBuilder.append("  - 接口类: ${usbInterface.interfaceClass}\n")
                detailBuilder.append("  - 子类: ${usbInterface.interfaceSubclass}\n")
                detailBuilder.append("  - 协议: ${usbInterface.interfaceProtocol}\n")
                detailBuilder.append("  - 端点数: ${usbInterface.endpointCount}\n")

                for (j in 0 until usbInterface.endpointCount) {
                    val endpoint: UsbEndpoint = usbInterface.getEndpoint(j)
                    val attr = endpoint.attributes
                    val syncType = (attr shr 2) and 0x03
                    val usageType = (attr shr 4) and 0x03
                    detailBuilder.append("    ▪ 端点 $j\n")
                    detailBuilder.append("      - 地址: ${endpoint.address}\n")
                    detailBuilder.append("      - 方向: ${endpointDirection(endpoint.direction)}\n")
                    detailBuilder.append("      - 类型: ${endpointType(endpoint.type)}\n")
                    detailBuilder.append("      - 最大包大小: ${endpoint.maxPacketSize}\n")
                    detailBuilder.append("      - 同步类型: ${syncTypeToStr(syncType)}\n")
                    detailBuilder.append("      - 使用方式: ${usageTypeToStr(usageType)}\n")
                }
                detailBuilder.append("\n")
            }

            binding.tvDeviceName.text = device.deviceName
            binding.tvSummary.text = baseInfo
            binding.tvDetails.text = detailBuilder.toString()
        } ?: run {
            binding.tvDeviceName.text = "无设备信息"
        }
    }

    override fun onDestroyView() {
        viewModel.updateUsbSerialDriver(null)
        super.onDestroyView()
    }

    private fun endpointDirection(direction: Int): String = when (direction) {
        UsbConstants.USB_DIR_IN -> "IN (设备到主机)"
        UsbConstants.USB_DIR_OUT -> "OUT (主机到设备)"
        else -> "未知"
    }

    private fun endpointType(type: Int): String = when (type) {
        UsbConstants.USB_ENDPOINT_XFER_CONTROL -> "控制传输"
        UsbConstants.USB_ENDPOINT_XFER_ISOC -> "等时传输"
        UsbConstants.USB_ENDPOINT_XFER_BULK -> "批量传输"
        UsbConstants.USB_ENDPOINT_XFER_INT -> "中断传输"
        else -> "未知"
    }

    private fun syncTypeToStr(value: Int) = when (value) {
        0 -> "无同步"
        1 -> "异步"
        2 -> "自适应"
        3 -> "同步"
        else -> "未知"
    }

    private fun usageTypeToStr(value: Int) = when (value) {
        0 -> "数据端点"
        1 -> "反馈端点"
        2 -> "显式反馈端点"
        3 -> "保留"
        else -> "未知"
    }
}